package com.iqiyi.pps.epg.core.service.auth;

import com.google.common.collect.Sets;
import com.iqiyi.pps.epg.core.model.auth.Authority;
import com.iqiyi.pps.epg.core.model.auth.Role;
import com.iqiyi.pps.epg.core.model.auth.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Set;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * 
 * @author calvin
 */
@Transactional(readOnly = true)
public class  UserDetailsServiceImpl extends LdapUserDetailsMapper implements UserDetailsService {

	private SysUserManager SysUserManager;

    /**
	 * 获取用户Details信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

		SysUser user = SysUserManager.findUserByLoginName(username);
		if (user == null) {
			throw new UsernameNotFoundException("用户" + username + " 不存在");
		}

		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

        user.setAuthorities(grantedAuths);
        user.setAccountNonExpired(true);
        user.setCredentialsNonExpired(true);
        user.setAccountNonLocked(true);

		return user;
	}

	/**
	 * 获得用户所有角色的权限集合.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(SysUser user) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		for (Role role : user.getRoleList()) {
			for (Authority authority : role.getAuthorityList()) {
				authSet.add(new GrantedAuthorityImpl(authority.getPrefixedName()));
			}
		}
        //获取自有权限
        for(Authority authority:user.getAuthList()){
            authSet.add(new GrantedAuthorityImpl(authority.getPrefixedName()));
        }
		return authSet;
	}

	@Autowired
	public void setSysUserManager(SysUserManager sysUserManager) {
		this.SysUserManager = sysUserManager;
	}

    @Override
    public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<GrantedAuthority> authorities) {
        UserDetails u = super.mapUserFromContext(ctx, username, authorities);
        //直接返回系统用户
        UserDetails su = this.loadUserByUsername(u.getUsername());
        return su;
    }
}
